import React, { createElement } from "react"
import { Menu } from "antd"
import { Link } from "react-router-dom"
import * as Icon from "@ant-design/icons"
const { SubMenu } = Menu

export const treeMenu = (list) => {
    var map = {},
        node,
        tree = []
    for (let i = 0; i < list.length; i++) {
        map[list[i].menuId] = list[i]
        list[i].children = []
    }
    for (let i = 0; i < list.length; i++) {
        node = list[i]
        if (node.pid !== 0) {
            map[node.pid].children.push(node)
        } else {
            tree.push(node)
        }
    }
    return tree
}


export const createMenu = (menu = []) => {
    const createIcon = (name) => createElement(Icon[name])
    const menuDom = menu.map(item => {
        if (item.children && item.children.length > 0) {
            return (
                <SubMenu key={item.menuId} title={item.menuName} icon={createIcon(item.icon)}>
                    {createMenu(item.children)}
                </SubMenu>
            )
        } else {
            return (
                <Menu.Item key={item.menuId} icon={createIcon(item.icon)}>
                    <Link to={item.pageUrl}>{item.menuName}</Link>
                </Menu.Item>
            )
        }
    })
    return menuDom
}